package newFeatureOfJava8;

/**
 * @author 26029
 * @date 2025/4/19
 * @description
 */
public class LearnLambda {
    public static void main(String[] args) {
        // 1. 匿名类:接口只有一个抽象方法(函数式接口)时可以使用 new(){@Override func(args)} 改为 (args)->{}
        Person1 person1 = new Person1("Tom");
        person1.getWing().fly();
        Person2 person2 = new Person2("Jack");
        person2.getWing().fly();
        // 2. lambda表达式本质上是一个对象
        Wing myWing = () -> {
            System.out.println("someone is flying");
        };
        // 3. 把方法引用作为lambda : 如过编写的 lambda 表达式所做的只是使用传递给 Lambda 的参数调用另一个方法
        // 引用类的静态方法的方法引用
        MyPrinter myPrinter1 = s -> System.out.println(s);
        MyPrinter myPrinter2 = System.out::println;
        // 参数方法的方法引用
        Finder finder1 = (s1, s2) -> s1.indexOf(s2);
        Finder finder2 = String::indexOf;
        // 构造方法的方法引用
        Factory factory1 = (chars) -> new String(chars);
        Factory factory2 = String::new;
    }
}

interface Wing {
    public int speed = 100;

    public void fly();
}

class Person1 {
    private Wing wing;
    private final String name;

    public Person1(String name) {
        this.name = name;
        // 可见性-使用匿名类:匿名类内部,this指接口,故拿不到匿名类外Person1类的String name
        this.wing = new Wing() {
            @Override
            public void fly() {
                System.out.println("This person is flying at a speed of " + this.speed + " km/h");
            }
        };
    }

    public String getName() {
        return name;
    }

    public Wing getWing() {
        return wing;
    }
}

class Person2 {
    private Wing wing;
    private final String name;

    public Person2(String name) {
        this.name = name;
        // 可见性-使用λ:this指Person2类,故可以拿到String name
        this.wing = () -> {
            System.out.println(this.name + " is flying at an unknown speed");
        };
    }

    public String getName() {
        return name;
    }

    public Wing getWing() {
        return wing;
    }
}

interface MyPrinter {
    public void print(String s);
}

interface Finder {
    public int find(String s1, String s2);
}

interface Factory {
    public String createString(char[] chars);
}